<template>
  <div>
    <el-dialog
      :title="type==='add'?'新增菜品':'编辑菜品'"
      :visible.sync="dialogVisible"
      width="800px"
      :close-on-click-modal="false"
      @close="close"
    >
      <div v-loading="loading" class="app-main-content-box business-store-edit">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" prop="icon">
          <el-form-item label="商品名称：" prop="name">
            <el-input v-model="form.name" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="商品预览图" prop="icon">
            <div class="cover-img">
              <el-upload
                :action="actionUrl"
                :show-file-list="false"
                :headers="uploadHeaders"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                class="app-uploader-img-plus"
              >
                <img v-if="form.icon" :src="fileBaseUrl+form.icon" class="avatar">
                <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
              </el-upload>
              <ul class="upload-tips">
                <li>图片要求：</li>
                <li>1.上传的图片限制文件大小限制1MB，仅支持JPG、PNG格式</li>
                <li>2.建议尺寸： 1000*1000像素</li>
              </ul>
            </div>
          </el-form-item>

          <el-form-item label="商品描述：" prop="desc">
            <el-input v-model="form.desc" :maxlength="30" placeholder="请输入商品描述" />
          </el-form-item>

          <el-form-item label="商品分类：" prop="categroy">
            <el-select v-model="form.categroy" class="selectb" placeholder="请选择">
              <el-option
                v-for="item in optionsOne"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
            <el-button type="text" size="mini" @click="addClassfication">新增分类</el-button>
          </el-form-item>
          <el-form-item
            v-if="!specificationItem"
            label="商品价格："
            prop="price"
            :rules="rules.specPrice"
          >
            <el-input v-model="form.price" class="priceb" placeholder="请输入内容">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="specificationItem" label="商品规格：" class="is-required" prop="itemNum">
            <!-- 规格列表 -->
            <ul>
              <li v-for="(item,index) in form.itemNum" :key="index" class="li-bo">
                <el-form-item
                  style="display:inline-block"
                  :prop="'itemNum.' + index + '.name'"
                  :rules="rules.specName"
                >
                  <el-input
                    v-model="item.name"
                    maxlength="20"  
                    show-word-limit
                    class="priceb ai-p"
                    placeholder="请输入规格属性"
                  />
                </el-form-item>
                <el-form-item
                  style="display:inline-block"
                  :prop="'itemNum.' + index + '.price'"
                  :rules="rules.specPrice"
                >
                  <el-input v-model="item.price" class="priceb ai-p" placeholder="请输入规格价格">
                    <template slot="append">元</template>
                  </el-input>
                </el-form-item>
                <el-button type="text" size="mini" round @click="deteleItem(index)">删除</el-button>
              </li>
            </ul>
          </el-form-item>
          <el-button
            :disabled="form.itemNum.length>=5"
            type="text"
            size="mini"
            class="add-left"
            round
            @click="addItem()"
          >+添加规格项目</el-button>
          <el-form-item label="商品属性：" prop="cloum">
            <el-select
              v-model="form.cloum"
              :multiple="true"
              :multiple-limit="3"
              class="selectb"
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-form>

        <el-button class="add-left" size="small" round @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" size="small" round @click="addComfim('form')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { imgUploadUrl } from '@/api/upload'
import {
  addGoods,
  searAllchClassiFication,
  searchAttributes,
  addClassiFication,
  searchGoodsByOne,
  updateGoods
} from '@/views/wcyModule/api/restaurant'
import { validateStrLen, validateMoney } from '@/utils/validate.js'
import { getShopInfo, createShop, updateShop } from '@/api/shop'
export default {
  data() {
    /**
       * 表单校验方法相关
       */
    const validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入商品名称'))
      } else if (!validateStrLen(value, 64)) {
        callback(new Error('长度不超过32个汉字或64个字符'))
      } else {
        callback()
      }
    }
    // const validateDesc = (rule, value, callback) => {
    //   if (value === "") {
    //     callback(new Error("请输入商品描述"));
    //   } else if (!validateStrLen(value, 64)) {
    //     callback(new Error("长度不超过32个汉字或64个字符"));
    //   } else {
    //     callback();
    //   }
    // };

    // 金钱校验
    const validateRmb = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入金额'))
      } else if (!validateMoney(value)) {
        callback(new Error('请输入正整数，正小数（小数位不超过2位）'))
      } else if (value - 999999.99 > 0) {
        callback('超过限额999999.99')
      } else {
        callback()
      }
    }

    return {
      // 配置
      resolve: null,
      reject: null,
      type: 'add',
      shopId: '',
      goodsId: '',
      //  状态
      dialogVisible: null,
      loading: false,
      // 数据
      // type: 'add',
      specificationItem: false,
      itemNum: [],
      optionsOne: [],
      options: [],
      value: '',
      catevalue: '',
      /**
         * 表单校验字段相关
         */
      rules: {
        // 名称
        name: [
          {
            required: true,
            validator: validateName,
            trigger: ['blur', 'change']
          }
        ],
        specName: [
          {
            required: true,
            message: '请输入规格属性',
            trigger: ['blur', 'change']
          }
        ],
        specPrice: [
          {
            required: true,
            validator: validateRmb,
            trigger: ['blur', 'change']
          }
        ],
        // desc: [
        //   {
        //     required: true,
        //     validator: validateDesc,
        //     trigger: ["blur", "change"]
        //   }
        // ],
        categroy: [
          {
            required: true,
            message: '请选择分类',
            trigger: ['blur', 'change']
          }
        ]
      },
      loading: false,
      actionUrl: imgUploadUrl,
      uploadHeaders: {},
      form: {
        icon: '',
        name: '',
        desc: '',
        price: '',
        categroy: '',
        cloum: [],
        itemNum: [],
        status: 1
      }
    }
  },
  computed: {
    ...mapGetters(['fileBaseUrl'])
  },
  methods: {
    editData() {
      searchGoodsByOne(this.goodsId, this.shopId).then(res => {
        if (res.code === 0) {
          this.form.name = res.data.name
          this.form.desc = res.data.description
          this.form.icon = res.data.imageName
          this.form.status = res.data.status
          this.shopId = res.data.shopId
          if (res.data.specList[0].name === 'DEFAULT') {
            this.form.price = res.data.specList[0].price / 100
          } else {
            this.form.itemNum = []
            const list = res.data.specList
            list.forEach(v => {
              this.form.itemNum.push({
                name: v.name,
                price: (v.price / 100).toFixed(2)
              })
            })
            this.specificationItem = true
          }
          searAllchClassiFication(this.shopId).then(rect => {
            this.optionsOne = []
            if (rect.code === 0) {
              const params = rect.data.row
              params.forEach((v, i) => {
                this.optionsOne.push({
                  value: v.name,
                  label: v.name,
                  id: v.id
                })
                if (v.id === res.data.classifyId) {
                  this.form.categroy = v.id
                }
              })
            }
          })
          searchAttributes(this.shopId).then(results => {
            this.options = []
            if (results.code === 0) {
              this.form.cloum = []
              const list = results.data
              const oldList = res.data.attrs.reverse()
              list.map((v, i) => {
                this.options.push({ value: v.name, label: v.name, id: v.id })
              })
              oldList.map((v, i) => {
                this.form.cloum.push(v.id)
              })
            }
          })
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      })
    },

    open(type, id, mid) {
      if (type === 'add') {
        this.type = type
        this.shopId = id
        this.specificationItem = false
        this.initData()
      } else if (type === 'edit') {
        this.type = type
        this.goodsId = id
        this.shopId = mid
        this.editData()
      }
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
      this.loading = false
      this.specificationItem = false
      this.form.itemNum = []
      this.form = {
        icon: '',
        name: '',
        desc: '',
        price: '',
        categroy: '',
        cloum: [],
        itemNum: [],
        status: 1
      }
      //  this.$refs.form.resetFields();
      this.$refs.form.clearValidate()
    },

    // 保存添加
    addComfim(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const attrs = []
          let params = ''
          this.form.cloum.forEach(v => {
            attrs.push({ id: v })
          })
          if (this.specificationItem === true) {
            const specList = []
            this.form.itemNum.forEach(v => {
              specList.push({
                name: v.name,
                price: this.$math.mul(v.price, 100, 0)
              })
            })
            params = {
              attrs: attrs,
              classifyId: this.form.categroy,
              description: this.form.desc,
              imageName: this.form.icon,
              status: this.form.status,
              name: this.form.name,
              ranknum: 0,
              shopId: this.shopId,
              specList: specList
            }
            if (this.goodsId !== '') {
              params.id = this.goodsId
            }
          } else if (this.specificationItem === false) {
            params = {
              attrs: attrs,
              classifyId: this.form.categroy,
              description: this.form.desc,
              imageName: this.form.icon,
              status: this.form.status,
              name: this.form.name,
              ranknum: 0,
              shopId: this.shopId,
              specList: [
                {
                  name: 'DEFAULT',
                  price: this.$math.mul(this.form.price, 100, 0)
                }
              ]
            }
            if (this.goodsId !== '') {
              params.id = this.goodsId
            }
          }

          if (this.type === 'add') {
            addGoods(params).then(res => {
              if (res.code === 0) {
                this.$notify({
                  title: '成功',
                  message: '添加成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.resolve()
                this.close()
              }
            })
          } else {
            updateGoods(params).then(res => {
              if (res.code === 0) {
                this.$notify({
                  title: '成功',
                  message: '编辑成功',
                  type: 'success',
                  duration: 2000,
                  offset: 40
                })
                this.resolve()
                this.close()
              }
            })
          }
        }
      })
    },

    // 新建分类
    addClassfication() {
      this.$prompt('请输入分类名称', '新建分类', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(({ value }) => {
          const data = {
            isValid: true,
            name: value,
            shopId: this.shopId,
            title: value
          }
          addClassiFication(data).then(res => {
            if (res.code === 0) {
              this.initData()
            }
          })
          this.$notify({
            title: '成功',
            message: '新增分类: ' + value,
            type: 'success',
            duration: 2000,
            offset: 40
          })
        })
        .catch(() => {})
    },

    // 获取数据
    initData() {
      searAllchClassiFication(this.shopId).then(res => {
        this.optionsOne = []
        if (res.code === 0) {
          const params = res.data.row
          params.map((v, i) => {
            this.optionsOne.push({ value: v.name, label: v.name, id: v.id })
          })
        }
      })
      searchAttributes(this.shopId).then(res => {
        this.options = []
        if (res.code === 0) {
          const list = res.data
          list.map((v, i) => {
            this.options.push({ value: v.name, label: v.name, id: v.id })
          })
        }
      })
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },

    // 删除规格
    deteleItem(index) {
      this.form.itemNum.splice(index, 1)
      if (this.form.itemNum.length === 0) {
        this.specificationItem = false
      }
    },

    // 添加规格
    addItem() {
      this.$refs.form.clearValidate(['price'])
      this.specificationItem = true
      this.form.itemNum.push({ name: '', price: '' })
    },

    /**
       * 按钮组
       */
    // 图片上传
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        this.form.icon = res.data.path
        this.$refs.form.clearValidate(['icon'])
      } else {
        this.$message.error(res.msg)
      }
    },

    // 上传预处理
    beforeAvatarUpload(file) {
      return this.beforeUploadImg(file, this, 1000, 1000, 1)
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  .business-store-edit {
    .el-input,
    .el-textarea {
      width: 70%;
      max-width: 600px;
    }

    .cover-img {
      display: flex;
      align-items: center;
      .app-uploader-img-plus {
        flex: 0 0 auto;
      }
    }

    .app-uploader-img-plus {
      width: 180px;
      height: 180px;
      .app-uploader-img-plus-icon {
        font-size: 36px;
        color: #8c939d;
        width: 180px;
        height: 180px;
        line-height: 180px;
        text-align: center;
      }
      .avatar {
        width: 180px;
        height: 180px;
        display: block;
      }
    }
    .upload-tips {
      margin: 10px 20px;
      li {
        margin: 5px 0;
        font-size: 14px;
        line-height: 16px;
        color: $dark-font-color;
      }
    }
  }
  .selectb {
    width: 460px !important;
  }
  .priceb {
    width: 200px !important;
  }
  .add-left {
    margin-left: 120px;
    margin-bottom: 22px;
  }
  .add-item {
    margin-left: -80px;
    margin-bottom: 22px;
  }
  .ai-p {
    margin-right: 20px;
  }
  .li-bo {
    margin-bottom: 20px;
  }
</style>
